//
//  LYLayout.m
//  MyProject
//
//  Created by yun on 2018/8/6.
//  Copyright © 2018年 yun. All rights reserved.
//

#import "LYLayout.h"

static CGFloat const Item_Width = 58;//116
static CGFloat const Item_Height = 80;//161

static CGFloat const ItemScaleRate = 0.4;


@implementation LYLayout

- (instancetype)init
{
    self = [super init];
    if (self) {
        [self setup];
    }
    return self;
}

- (void)setup{
    CGFloat margin = (kScreenWidth - Item_Width)/2.f;
    self.itemSize = CGSizeMake(Item_Width, Item_Height);
    self.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    self.sectionInset = UIEdgeInsetsMake(0, ABS(margin), 0, ABS(margin));// 居中
    self.minimumLineSpacing = 30;
}

- (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds{
    return YES;
}

- (NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect{
    NSArray *attrs = [super layoutAttributesForElementsInRect:rect];
    CGRect visibleRect;// collectionview可见区域
    visibleRect.origin = self.collectionView.contentOffset;
    visibleRect.size = self.collectionView.bounds.size;
    
    for (UICollectionViewLayoutAttributes *attr in attrs) {
        if (CGRectIntersectsRect(attr.frame,visibleRect)) {// 是否相交（在界面显示绝对相交）
            CGFloat offsetX = CGRectGetMidX(visibleRect) - attr.center.x;// item距中心的距离
            CGFloat scale = 1 + ItemScaleRate * (1 - 2 * ABS(offsetX)/kScreenWidth);
            attr.transform3D = CATransform3DMakeScale(scale, scale, 1);
        }
    }
    
    return attrs;
}

// 偏移量
- (CGPoint)targetContentOffsetForProposedContentOffset:(CGPoint)proposedContentOffset withScrollingVelocity:(CGPoint)velocity{
    CGRect targetRect;
    targetRect.origin = proposedContentOffset;
    targetRect.size = self.collectionView.bounds.size;

    NSArray *attrs = [super layoutAttributesForElementsInRect:targetRect];// 滑动到目标区域时的attrs
    // 找出距离屏幕中点最近的item adjustOffset每次循坏会重新赋值，一直到最近距离
    CGFloat adjustOffset = MAXFLOAT;
    for (UICollectionViewLayoutAttributes *attr in attrs) {
        if (CGRectIntersectsRect(attr.frame, targetRect)) {
            CGFloat itemCenterX = attr.center.x;
            CGFloat distance = CGRectGetMidX(targetRect) - itemCenterX;// 中点距item中点距离
            if (ABS(distance) < adjustOffset) {
                adjustOffset = distance;// 负：item在中心点右侧；正：item在中心点左侧
            }
        }
    }
    
    CGPoint point = CGPointMake(proposedContentOffset.x - adjustOffset, proposedContentOffset.y);
    return point;
}



@end
